package com.sikaryofficial.backend.service.guidetask;

import com.sikaryofficial.backend.config.GuideTaskConfig;
import com.sikaryofficial.backend.domain.dto.req.points.GuideTaskReq;
import com.sikaryofficial.backend.domain.entity.GuideTaskDetail;
import com.sikaryofficial.backend.service.IGuideTaskDetailService;
import com.sikaryofficial.backend.service.IPointsDetailStrategy;
import com.sikaryofficial.backend.service.email.notice.GuildTaskNoticeService;
import com.sikaryofficial.common.core.constant.PointRuleConstant;
import com.sikaryofficial.common.core.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@Service
public class GuideTaskProcess {

	@Autowired
	private IGuideTaskDetailService guideTaskDetailService;

	@Autowired
	private GuildTaskNoticeService guildTaskNoticeService;

	@Autowired
	private GuideTaskConfig guideTaskConfig;

	@Resource
	private Map<String, IPointsDetailStrategy> pointsDetailStrategyMap;

	public void processGuideTask(GuideTaskReq guideTaskReq) {
		Long userId = guideTaskReq.getUserId();
		// 查询指定任务
		GuideTaskDetail guideTaskDetail = guideTaskDetailService.lambdaQuery().eq(GuideTaskDetail::getTaskCode, guideTaskReq.getTaskCode()).eq(GuideTaskDetail::getCreatedBy, userId).eq(GuideTaskDetail::getDeletedVersion, 0).one();
		if (Objects.nonNull(guideTaskDetail)) {
			return;
		}
		Integer points = guideTaskConfig.getPointsByTaskCode(guideTaskReq.getTaskCode());
		if (points.equals(0)) {
			throw new ServiceException("Unknown Task");
		}
		guideTaskDetail = guideTaskDetailService.saveGuideTask(guideTaskReq);
		IPointsDetailStrategy pointsDetailStrategy = pointsDetailStrategyMap.get(PointRuleConstant.GUIDE_TASK + IPointsDetailStrategy.SUFFIX);
		pointsDetailStrategy.updatePointsByInputValue(guideTaskDetail.getGuideTaskDetailId(), userId, points, null, guideTaskDetail.getTaskCode());
		guildTaskNoticeService.guideEmailNotice(userId, points);
	}
}
